package cloud.lysky.java.on.concurrent.cas;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author luoly
 * @describe
 * @date 2022-10-21 21:47
 **/
public class UnsafeFactory {

    private UnsafeFactory(){

    }

    private static volatile  Unsafe INSTANCE;

    public static Unsafe getUnsafe() {
        if (INSTANCE == null){
            synchronized (UnsafeFactory.class){
                if (INSTANCE == null){
                    try {
                        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
                        theUnsafe.setAccessible(true);
                        //如果field的name是一个static的变量，field.get(param)，
                        // param是任意的都可以，返回类中当前静态变量的值。
                        //如果是非静态变量，field.get(obj)，obj必须是当前类的实例对象
                        //返回实例对象obj的变量值。
                        return (Unsafe) theUnsafe.get(null);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            }
        }
        return INSTANCE;
    }
}